<template>
	<view class="container">
		<view class="head-top" v-if="type == 1">
			<view style="margin-left: 2%;" @tap="goBack()">
				<u-icon name="arrow-leftward" size='20' />
				</u-icon>
			</view>
			<view>通讯录</view>
			<text style="font-size: 34px;line-height: 16px;height: 40px;">
			</text>

		</view>
		<view class="head-top" v-else-if="type == 2">
			<view style="margin-left: 2%;" @tap="goBack()">
				关闭
			</view>
			<view>选择一个聊天</view>
			<text style="font-size: 34px;line-height: 16px;height: 40px;">
			</text>

		</view>
		<view>
			<scroll-view scroll-y class="list" v-if="type == 1">
				<u-index-list :index-list="validIndexList" v-if="itemArr.length > 0">
					<template v-for="(item, index) in validItemArr">
						<!-- #ifdef APP-NVUE -->
						<u-index-anchor :text="validIndexList[index]"></u-index-anchor>
						<!-- #endif -->
						<u-index-item>
							<!-- #ifndef APP-NVUE -->
							<u-index-anchor :text="validIndexList[index]"></u-index-anchor>
							<!-- #endif -->
							<view class="list-cell" v-for="(cell, index) in item" @tap="toDetail(cell)">
								<!-- 此处是具体列表项内容保持不变 -->
								<view v-if="user.face">
									<image :src="user.face" class="face"></image>
								</view>
								<view v-else>
									<view class="name-img">{{cell.nickname[0]}}</view>
								</view>
								<view style="margin-left: 50upx; font-weight: 300;">
									<view style="font-size: 24upx;">{{cell.nickname}}</view>
									<view style="font-size: 24upx;">在线</view>
								</view>
							</view>
						</u-index-item>
					</template>
				</u-index-list>
			</scroll-view>
			<scroll-view scroll-y class="list" v-else-if="type == 2">
				<u-index-list :index-list="validIndexList" v-if="itemArr.length > 0">
					<template v-for="(item, index) in validItemArr">
						<!-- #ifdef APP-NVUE -->
						<u-index-anchor :text="validIndexList[index]"></u-index-anchor>
						<!-- #endif -->
						<u-index-item>
							<!-- #ifndef APP-NVUE -->
							<u-index-anchor :text="validIndexList[index]"></u-index-anchor>
							<!-- #endif -->
							<view class="list-cell" v-for="(cell, index) in item" @tap="toSend(cell)">
								<!-- 此处是具体列表项内容保持不变 -->
								<view v-if="user.face">
									<image :src="user.face" class="face"></image>
								</view>
								<view v-else>
									<view class="name-img">{{cell.nickname[0]}}</view>
								</view>
								<view style="margin-left: 50upx; font-weight: 300;">
									<view style="font-size: 24upx;">{{cell.nickname}}</view>
									<view style="font-size: 24upx;">在线</view>
								</view>
							</view>
						</u-index-item>
					</template>
				</u-index-list>
			</scroll-view>
		</view>

		<view class="" v-if="sendShow" style="width: 100%;height: 100%;position: fixed;top: 0;left: 0;z-index: 999;">
			<!-- <u-popup :show="sendShow" @close="sendClose" :closeOnClickOverlay="true" mode="center" :round="20"> -->
			<view class="mask" hover-class="none" @tap="sendClose()"></view>

			<view class="clear-record-box">
				<view class="clear-record-box-title">发送给</view>
				<view class="clear-record-box-title1">
					<view style="display: flex;align-items: center;">
						<view class="name-img">{{senditem.nickname[0]}}</view>
						<view style="flex:1; 50upx; font-weight: 300;font-size: 24upx;">{{senditem.nickname}}
						</view>

					</view>
					<view style="margin: 5px 0;">{{message_list[0].str}}</view>

				</view>
				<view class="clear-record-box-btn">
					<view class="clear-record-box-btn-left" @tap="sendClose()">取消</view>
					<view class="clear-record-box-btn-right" @tap="sendConFirm()">确定</view>
				</view>
			</view>
			<!-- </u-popup> -->

		</view>
	</view>
</template>

<script>
	import StringTool from "../../tools/StringTool";
	export default {
		components: {
			
		},
		data() {
			return {
				sendShow: false, //聊天记录
				senditem: {},

				user: {},
				dirlogShow: false,
				list: [{
						friendName: 'aaa',
					},
					{
						friendName: 'bbb',
					},
					{
						friendName: 'ccc',
					},
					{
						friendName: 'ddd',
					}
				],
				telephone: '',
				baseList: [{
						name: 'photo',
						title: '新的朋友',
						url: '../../static/image/group@3x.png'
					},
					{
						name: 'lock',
						title: '我的群组',
						url: '../../static/image/new-user@3x.png'
					},
					{
						name: 'star',
						title: '标签分组',
						url: '../../static/image/tag@3x.png'
					},
				],
				indexList: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
					"T", "U", "V", "W", "X", "Y", "Z"
				],
				itemArr: [],

				type: '',
				message_item: {},
				message_list: [],
			}
		},
		computed: {
			validIndexList() {
				if (this.itemArr && this.itemArr.length > 0) {
					return this.indexList.filter((_, index) => this.itemArr[index] && this.itemArr[index].length > 0);
				}
				return []; // 如果 itemArr 不符合条件（为空或者元素未定义等），返回空数组
			},
			validItemArr() {
				return this.itemArr.filter(item => item && item.length > 0);
			}
		},
		onLoad(options) {
			console.log(options);
			if (options.type) {
				this.type = options.type
			}
			if (options.message_item) {

				console.log(options.message_item);
				this.message_list = JSON.parse(options.message_item)
			}
			const eventChannel = this.getOpenerEventChannel();
			eventChannel.on('sharefriend', (params) => {
				console.log(params);
				this.message_list = params.data;
			console.log(this.message_list);
			})
			this.selectTableData();


			// this.getfriendlist()
			// #ifdef MP-WEIXIN
			let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
			this.posRight = (menuButtonInfo.width + 20) + 'px'
			// #endif
			//// this.getList()


		},
		onShow() {
			let pages = getCurrentPages();
			if (pages.length < 2) {
				uni.switchTab({
					url: '/pages/message/index'
				})
			}

		},
		methods: {
			// 查询表数据
			async selectTableData() {

				let open = this.DB.isOpen();
				console.log("open-=-=-=-==-==-", open);
				if (open) {
					// 查询表 DB.selectTableData(表名,查询条件列名,查询条件列值)
					let userinfo;
					this.DB.selectTableData("friend" + uni.getStorageSync("user_uid"))
						.then(res => {
							console.log("contact表数据-=-=-=-==-==-", res);
							let originalArray = res
							this.indexList.forEach((char, index) => {
								this.itemArr.push(originalArray.filter(f => StringTool.getFirstLetter(f
									.nickname).charAt(0).toUpperCase() === char))

							})


						})
						.catch(error => {
							console.log("查询失败", error);
							this.getList()

						});
				} else {
					// this.$util.toast("数据库未打开");
					this.DB.openSqlite()
						.then(res => {
							console.log("数据库已打开");
						})
						.catch(error => {
							console.log("数据库开启失败");
						});
				}
			},
			// 获取好友
			getfriendlist() {
				this.$util.loading('加载中')
				// const newDataObj = {
				// 	"user_uid": uni.getStorageSync('user_uid'),
				// };
				// const newDataJsonStr = JSON.stringify(newDataObj)
				const requestData = {
					"processorId": '1008',
					"jobDispatchId": '2',
					"actionId": '7',
					"newData": uni.getStorageSync('user_uid')
				};
				const requestDataJsonStr = JSON.stringify(requestData);
				uni.request({
					url: 'http://chat.zwsmcn.com:8090/rest_post',
					header: {
						'content-type': 'application/json'
					},
					data: requestDataJsonStr,
					method: 'POST',
					success: res => {
						console.log(JSON.parse(res.data.returnValue))
						uni.hideLoading()



						let originalArray = JSON.parse(res.data.returnValue)
						console.log(originalArray)
						this.indexList.forEach((char, index) => {
							this.itemArr.push(originalArray.filter(f => StringTool.getFirstLetter(f
								.nickname).charAt(0).toUpperCase() === char))

						})

						originalArray.map(item => {
							let nicknamehashMap = new Map();;


							nicknamehashMap.set(item.user_uid, item.nickname);

							let avatarhashMap = new Map();

							avatarhashMap.set(item.user_uid, item.userAvatarFileName);
							uni.setStorageSync('avatarhashMap', JSON.stringify(Array.from(
								avatarhashMap)))
							uni.setStorageSync('nicknamehashMap', JSON.stringify(Array.from(
								nicknamehashMap)))
							console.log(avatarhashMap.get(item.user_uid));


						})

						console.log(this.indexList)
					},
					fail: res => {
						console.log(res);
					}
				});
			},
			// 取消添加
			cancelAdd() {
				this.$refs.addFriend.close()
				this.telephone = ''
			},
			// 添加好友
			addFriend() {
				this.$refs.addFriend.open()
			},
			addFriendAction() {
				if (!this.$validate.isPhone(this.telephone)) {
					return this.$util.toast('手机号格式错误')
				}

				this.$util.loading('添加中')
				uni.request({
					method: 'POST',
					url: this.$api.addFriend,
					data: {
						userId: uni.getStorageSync('userId'),
						telephone: this.telephone
					},
					header: this.$util.getHeader(),
					success: res => {
						uni.hideLoading()
						if (res.data.code) {
							return this.$util.toast(res.data.msg)
						}
						this.$refs.addFriend.close()
						this.telephone = ''
						// this.getList()
					},
					fail: err => {
						uni.hideLoading()
						this.$util.toast('添加失败')
					}
				})
			},
			toSend(item) {
				console.log(item)
				this.senditem = item
				this.sendShow = true
			},

			sendClose() {
				this.sendShow = false
				// console.log('close');
			},
			sendConFirm() {

				for (let ii = 0; ii < this.message_list.length; ii++) {
					this.message_item = this.message_list[ii];
					console.log(this.message_item);

					let at = [];
					let contentDuration = 0;
					let srcNickName = uni.getStorageSync('nickname') ?? '';
					let typeu = 3;
					let chat_type = this.message_item.contentType

					let dataContent = this.senddataContent(typeu, this.message_item.dataContent, chat_type, at);
					let p = uni.MBProtocalFactory.createGroupDataSimple(uni.IMSDK.getLoginInfo().loginUserId,
						srcNickName, this.senditem.user_uid, dataContent,
						typeu, at, chat_type, Math.ceil(contentDuration / 1000));

					console.log(p);
					// return;
					uni.IMSDK.sendData(p);

					// uni.navigateBack();
					let pages = getCurrentPages();
					if (pages.length >= 2) {
						p.nickname = this.senditem.nickname;
						p.avatar = this.senditem.userAvatarFileName;
						p.gid = 0;

						let prePage = pages[pages.length - 2]; // 上一页面
						prePage.$vm.insertTableData(p);

						// uni.navigateBack();
					}

					this.sendShow = false
					if (ii == this.message_list.length - 1) {
						let prePage = pages[pages.length - 2]; 
						prePage.$vm.resetmore();
						uni.navigateBack();
					}
				}


				// this.sendShow = false
			},
			senddataContent(typeu, dataContent, chat_type, contentDuration, at) {
				let from_user_id = uni.IMSDK.getLoginInfo().loginUserId;
				let to_user_id = this.senditem.user_uid;
				let from_user_nickname = uni.getStorageSync('nickname') ?? '';;
				let from_user_avatar = uni.getStorageSync('user_avatar_file_name') ?? '';;

				var dataContent_z = {};
				let fingerPrint = null
				let QoS = true;
				if (typeu == 3) {
					dataContent_z.t = to_user_id;
					dataContent_z.cy = 2;
					dataContent_z.m = dataContent;
					dataContent_z.ty = chat_type;
					dataContent_z.quote_status = 0;
					dataContent_z.quote_type = 0;
					dataContent_z.quote_fp = '';
					dataContent_z.quote_sender_uid = '';
					dataContent_z.quote_sender_nick = '';
					dataContent_z.quote_content = ''; //quote_content
					dataContent_z.f = from_user_id;
					if (chat_type == 2) {
						dataContent_z.contentDuration = contentDuration;
					}

					dataContent_z.nickName = from_user_nickname;
					dataContent_z.userAvatar = from_user_avatar;
					dataContent_z.receivernickName = this.senditem.nickname ?? '';
					dataContent_z.receiveruserAvatar = this.senditem.userAvatar ?? '';
				} else {
					dataContent_z.at = at;
					dataContent_z.QoS = QoS;
					dataContent_z.nickName = from_user_nickname;
					dataContent_z.userAvatar = from_user_avatar;
					dataContent_z.receivernickName = this.senditem.g_name;
					dataContent_z.receiveruserAvatar = '';
					dataContent_z.cy = 2;
					dataContent_z.f = from_user_id;
					dataContent_z.m = dataContent;
					dataContent_z.t = to_user_id;
					dataContent_z.ty = chat_type;
					dataContent_z.quote_status = 0;
					dataContent_z.quote_type = 0;
					dataContent_z.quote_fp = '';
					dataContent_z.quote_sender_uid = '';
					dataContent_z.quote_sender_nick = '';
					dataContent_z.quote_content = '';
					if (chat_type == 2) {
						dataContent_z.contentDuration = contentDuration;
					}


				}

				return dataContent_z;
			},

			// 详情
			toDetail(item) {
				console.log(item)
				let user_uid = item.user_uid

				let pages = getCurrentPages();
				if (pages.length >= 2) {


					let prePage = pages[pages.length - 2]; // 上一页面
					prePage.$vm.getcontactinfo(JSON.stringify(item));

					uni.navigateBack();
				}
			},
			// 获取好友列表
			// getList() {
			// 	this.$util.loading('加载中')
			// 	uni.request({
			// 		method: 'POST',
			// 		url: this.$api.getFriends,
			// 		data: {
			// 			userId: uni.getStorageSync('userId')
			// 		},
			// 		header: this.$util.getHeader(),
			// 		success: res => {
			// 			uni.hideLoading()
			// 			this.list = res.data.data
			// 		},
			// 		fail: err => {
			// 			uni.hideLoading()
			// 			this.$util.toast('获取失败')
			// 		}
			// 	})
			// },
			
			handleDirlog() {
				this.dirlogShow = true
			},
		}
	}
</script>

<style lang="scss" scoped>
	// ::v-deep .u-index-list__letter {
	// 	margin-top: 120px !important;
	// }
	.head-top {
		width: 100%;
		height: 148upx;
		margin: 0 auto;
		// background: #ffffff;
		display: flex;
		justify-content: space-between;
		align-items: center;
		z-index: 999999;
		background-color: #FFF;
		margin-top: 40upx;
	}

	.container {
		width: 100%;
		height: 100%;
	}

	.head {
		// margin-top: 30upx;
	}

	.tab-box {
		margin-top: 60upx;

		image {
			width: 90upx;
			height: 90upx;
			// background-color: #000;
			border-radius: 12upx;
			padding: 16upx;
			opacity: 0.7;
		}
	}

	.tab-icon {
		width: 70upx;
		height: 70upx;
		border-radius: 10upx;
	}

	.grid-text {
		font-size: 14px;
		color: #909399;
		padding: 10rpx 0 20rpx 0rpx;
		/* #ifndef APP-PLUS */
		box-sizing: border-box;
		/* #endif */
	}

	.add-friend {
		width: 600upx;
		height: 460upx;
		padding: 0 40upx;
		border-radius: 10upx;
		background-color: #FFF;
		position: relative;

		.close {
			position: absolute;
			right: 20upx;
			top: 20upx;
		}

		.title {
			height: 120upx;
			font-size: 30upx;
			text-align: center;
			line-height: 120upx;
		}

		.input {
			height: 80upx;
			padding: 0 30upx;
			border-radius: 10upx;
			margin: 40upx 0 80upx;
			border: 2upx solid #ddd;
		}

		.btn {
			color: #FFF;
			height: 80upx;
			line-height: 80upx;
			text-align: center;
			border-radius: 10upx;
			background-color: #2CA246;

			&.disabled,
			&:active {
				opacity: 0.8;
			}
		}
	}

	.list {
		height: calc(100vh - 350upx);

		.item {
			width: 100vw;
			padding: 20upx 30upx 0;
			box-sizing: border-box;

			.cover {
				width: 80upx;
				height: 80upx;
				border-radius: 10upx;
				box-sizing: border-box;
				border: 2upx solid #f9f9f9;
				position: relative;

				.icon {
					width: 100%;
					height: 100%;
					border-radius: 10upx;
				}
			}

			.title {
				height: 100%;
				box-sizing: border-box;
				width: calc(100vw - 110upx - 60upx);
				position: relative;

				&::after {
					content: '';
					width: 100%;
					height: 2upx;
					background-color: #F6F6F6;
					position: absolute;
					left: 0;
					bottom: -34upx;
				}

				.main {
					margin: 6upx 0;

					.text {
						color: #333;
						font-size: 32upx;
						font-weight: 600;
					}

					.time {
						color: #666;
						font-size: 24upx;
					}
				}
			}
		}
	}

	.search-box {
		width: 60%;
		background-color: #fff;
		margin-top: 20upx;
		color: #2e2e2e;

	}

	.list-cell {
		display: flex;
		box-sizing: border-box;
		width: 100%;
		padding: 10px 24rpx;
		overflow: hidden;
		color: #323233;
		font-size: 14px;
		line-height: 24px;
		background-color: #fff;

		image {
			width: 100upx;
			height: 100upx;
			border-radius: 50%;
		}
	}

	::v-deep .u-index-anchor {
		background-color: #fff !important;
		border: none;
	}

	.name-img {
		width: 90upx;
		height: 90upx;
		border-radius: 50%;
		background: rgb(0, 212, 226);
		font-size: 36upx;
		text-align: center;
		line-height: 90upx;
		color: #fff;
		margin-left: 10upx;
		margin-top: -10upx;
	}

	.dirlog-box {
		width: 40%;
		background: #fff;
		border-radius: 20upx;
		padding: 10upx 30upx;
		box-shadow: 0 0 40upx #000; // 左
		box-shadow: 0 0 40upx #000; // 右
		color: #2e2e2e;
		font-weight: 300;
		position: absolute;
		right: 3%;
		top: 11%;
		z-index: 1;

		.dirlog-box1 {
			display: flex;
			padding: 30upx 10upx;

			image {
				width: 60upx;
				height: 60upx;
			}

			view {
				margin-left: 20upx;
			}
		}
	}

	.clear-record-box {
		border-radius: 30upx;
		padding: 30upx;
		width: 90%;

		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 9999;
		background-color: #ffffff;

		.clear-record-box-title {
			padding: 10upx 20upx;
			font-size: 40upx;
		}

		.clear-record-box-title1 {
			padding: 20upx 0 30upx 20upx;
			font-size: 30upx;
			font-weight: 300;
		}

		.clear-record-box-btn {
			display: flex;
			// padding: 30upx 0 20upx 0;
			justify-content: space-between;
			position: relative;

		}

		.clear-record-box-btn-left {
			width: 50%;
			text-align: center;
			color: #999;
		}

		.clear-record-box-btn-right {

			color: #000;
			width: 50%;
			text-align: center;
		}
	}

	.mask {
		position: fixed;
		top: 0;
		width: 100%;
		height: 100%;
		z-index: 100;
		background-color: rgba(0, 0, 0, 0.4);
	}
</style>